import { ElMessage } from 'element-plus';

export interface SseFetchOptions {
  headers?: Record<string, string>;
  onmessage: (data: string) => void;
  onerror?: (err: any) => void;
  signal?: AbortSignal;
}

export default async function useSseFetch(url: string, options: SseFetchOptions) {
  const { headers = {}, onmessage, onerror, signal } = options;

  try {
    const res = await fetch(url, {
      headers: {
        ...headers,
        Authorization: `Bearer ${useUserStore().token}`,
      },
      method: 'GET',
      signal,
    });

    if (res.status === 401) {
      useUserStore().onLogout();
      ElMessage.error('登录失效，请重新登录');
      navigateTo('/login');
      return Promise.reject(new Error());
    }
    if (res.status !== 200) {
      const data = await res.json();
      ElMessage.error((data.message as string) || '执行失败，请反馈或稍后再试');
      return Promise.reject(new Error());
    }

    const reader = res.body!.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      let eol;
      while ((eol = buffer.indexOf('\n')) >= 0) {
        const line = buffer.slice(0, eol).trim();
        buffer = buffer.slice(eol + 1);

        if (line.startsWith('data:')) {
          const data = line.slice(5).trim();
          onmessage(data);
        }
        if (line.startsWith('event')) {
          onerror?.('执行失败');
          return Promise.reject(new Error());
        }
      }
    }
  } catch (err) {
    onerror?.(err);
  }
}
